<?php
class SiteController extends Controller {
    
    /**
     * Declares class-based actions.
     */
    public function init() {
        parent::init();
        $this->R->module = "系统操作";
    }
    
    public function actions() {
        
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
   //             'clickableImage' => true,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }
//
    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('index'),
                'users' => array('*'),
            )/*,
            array('allow',
                'actions' => array('regist','login'),
                'users' => array('?'),
            )*/
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {

        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        $this->render('index');
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                $headers = "From: {$model->email}\r\nReply-To: {$model->email}";
                mail(Yii::app()->params['adminEmail'], $model->subject, $model->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {

        if ($this->checkSession())
        {
            $this->redirect(Yii::app()->user->returnUrl);
        }

        $model = new LoginForm;
        
        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
   
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        // collect user input data
        if (isset($_POST['LoginForm']) ) {
            $this->R->action = "登陆系统";
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
            {
                $this->R->success = true; 
                $this->R->data["returnUrl"] = Yii::app()->user->returnUrl;
          //        $this->redirect(Yii::app()->user->returnUrl);
            }
            $this->R->flush();
        }


        // display the login form
        $this->render('login', array('model' => $model));
    }

    public function actionRegist() {
        //查看session
       if ($_POST)
		 {
			$captcha = trim($_POST['captcha']);
        	$record = $this->createAction('captcha')->validate($captcha, false);       
        	 if (!$record)
	        {
	            $this->render('regist');exit;
	        }        
	        $email = trim($_POST['email']);
	        $record = User::model()->findByAttributes(array('Email'=>$email));
	        if ($record)
	        {
	            $this->render('regist');exit;
	        }
	        if (isset($_POST['emial'])) {
	        	$mail = new PHPMailer(true); 
	        	$mail->IsSMTP();
	        	$mail->SMTPAuth   = true;
	        	$mail->SetFrom('lcjyp2007@163.com', 'system');
	        	$mail->Subject = '欢迎注册天校网';

	        	// $mail->AddAttachment('class.pop3.php');
	        	$user = new User;
	        	//          $user->Name = trim($_POST['name']);
	        	$user->Name = trim($_POST['email']);
	        	$user->Password = md5($_POST['password']);
	        	//       $user->School = trim($_POST['school']);
	        	$user->Email = trim($_POST['email']);
	        	$user->ActiveCode = $this->getCode();
	        	$user->Status = 0;
	        	$body = "欢迎注册天校网,请点击下面这里进行激活<br/>http://localhost/web/index.php?r=site/active/user/".$user->Name.'/code/'.base64_encode($user->ActiveCode);
	        	$mail->MsgHTML($body);
	        	$mail->AddAddress($user->Email, $user->Name);
	        	if ( $mail->Send() && $user->save())
	        	{
	        		$this->render('resit_result',array('result'=>'注册成功','s'=>5,'url'=>'?r=site/login'));
	        	}
	        	else
	        	{
	        		$this->render('resit_result',array('result'=>$user->getErrors(),'s'=>3,'url'=>'?r=site/regist'));
	        	}
	        }
		}else {
			$this->render('regist');
		}
        
    }
    //checkEmail

    public function actionCheckEmail(){
        $email = trim($_POST['email']);
        $record = User::model()->findByAttributes(array('Email'=>$email));
        if ($record)
        {
            echo 'false';
        }
        else
        {
            echo 'true';
        }
        exit;
    }
    //checkCaptcha    
    public function actionCheckCaptcha(){
        $captcha = trim($_POST['captcha']);
        $record = $this->createAction('captcha')->validate($captcha, false);
        if ($record)
        {
            echo 'true';
        }
        else
        {
            echo 'fasle';
        }
        exit;
    }
    public function actionActive(){
        $username = $this->getParam('user');
        $code = base64_decode($this->getParam('code'));
        $user = User::model()->find("`Name`='{$username}' AND `ActiveCode` = '{$code}'");
        $r = User::model()->updateByPk($user->ID,array('Status'=>1));
        if ($r)
        {
            $this->render('resit_result',array('result'=>'激活成功','s'=>5,'url'=>'?r=site/login'));
        }
        else
        {
            $this->render('resit_result',array('result'=>'激活失败！','s'=>5,'url'=>'?r=site/login'));
        }
    
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        
        $this->redirect(Yii::app()->homeUrl);
    }

    public function getCode( $length = 8) { 
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|'; 

        $password = ''; 
        for ( $i = 0; $i < $length; $i++ ) 
        { 
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ]; 
        } 
        return $password; 
    }
    public function checkSession(){
    	$record = User::model()->findByAttributes(array('Name'=>Yii::app()->session['username'],'Password'=>Yii::app()->session['password']));
    	if($record)
    	return true;
    	return false;
    }
}